package com.itheima.reggie.common;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.io.IOException;
import java.sql.SQLIntegrityConstraintViolationException;
import java.util.Arrays;

@RestControllerAdvice(annotations = {RestController.class, Controller.class})
@Slf4j
public class GlobaExeptionHandler {

    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public R<String> exeptionHandler(SQLIntegrityConstraintViolationException e){
        // Duplicate entry 'pengjin'
        //捕获到添加员工时出现重复用户名错误信息
        if(e.getMessage().contains("Duplicate entry")){
            log.info(e.getMessage());
            String[] msg = e.getMessage().split(" ");
            return R.error(msg[2]+"已存在");
        }

        return R.error(e.getMessage());
    }


    /**
     * 自定义捕获的异常
     * @param e
     * @return
     */
    @ExceptionHandler(CustomException.class)
    public R<String> exeptionHandler(CustomException e){
        return R.error(e.getMessage());
    }

    /**
     * 捕捉上传图片IO异常
     * @param e
     * @return
     */
    @ExceptionHandler(IOException.class)
    public R<String> exeptionHandler(IOException e){
        return R.error("服务器图片目录错误");
    }
}
